<?php

namespace SunAdmin\Controller;

use think\Request;
use SunAdmin\Common\ResponseJson;
use SunAdmin\Common\TokenHelper;
use SunAdmin\Model\AccountGroupModel;
use SunAdmin\Service\AccountService;
use think\facade\Cache;

class AccountController
{
    public function login(Request $request)
    {
        $data = request()->param([
            'username'=>'','password'=>'',
        ]);
        try {
            $accountInfo = AccountService::login($data['username'], $data['password']);
            return ResponseJson::success($accountInfo,'登录成功');
        } catch (\Exception $e) {
            return ResponseJson::error('登录失败,'.$e->getMessage());
        }
    }

    public function loginOut(Request $request)
    {
        $tokenToClear = null;
        $authHeader = $request->header('authorization');

        if ($authHeader && str_starts_with(strtolower($authHeader), 'bearer ')) {
            $tokenToClear = substr($authHeader, 7);
        } else {
            $paramToken = $request->param('token');
            if ($paramToken) {
                $tokenToClear = $paramToken;
            }
        }

        if ($tokenToClear) {
            try {
                Cache::delete($tokenToClear);
            } catch (\Exception $e) {
                // 可选：记录删除缓存失败的日志，但不应中断登出流程
                // trace('登出时从缓存清除Token失败: ' . $e->getMessage(), 'error');
            }
        }

        return ResponseJson::success('退出成功');
    }

    public function tokenAuth(Request $request)
    {
        $info = $request->adminUser->toArray();
        $info['menusList'] = AccountService::getAccountMenusList($info['group_id']);
        return ResponseJson::success($info);
    }
	
	/**
	 * 获取管理员权限组列表
	 * 不分页
	 */
	public function getGroupList(){
		$list = AccountService::getGroupList();
		return ResponseJson::success($list);
	}
	
	/**
	 * 创建/编辑管理员权限分组
	 */
	public function editAccountGroup() {
		$data = request()->param([
			'id'=>'',
			'name'=>'','status'=>1,'remark'=>'','menus_ids'=>'','tree_menus_ids'=>'',
		]);
		AccountService::editAccountGroup($data);
		return ResponseJson::success('操作成功');
	}
	
	/**
	 * 删除管理员角色组
	 */
	public function deleteAccountGroup($groupId) {
		AccountService::deleteAccountGroup($groupId);
		return ResponseJson::success('删除成功');
	}
	
	public function getAccountList() {
		$where = ['is_del'=>0];
		$res = AccountService::getAccountList($where);
		return ResponseJson::success($res);
	}
	
	public function editAccount() {
		$data = request()->param([
			'id'=>0,'avatar'=>'','username'=>'','password'=>'','passwordConfirm'=>'',
			'nickname'=>'','group_id'=>'','status'=>1,'remark'=>''
		]);
		AccountService::editAccount($data);
		return ResponseJson::success('编辑账号成功');
	}
	
	public function delAccount($accountId) {
		AccountService::delAccount($accountId);
		return ResponseJson::success('删除成功');
	}

    /**
     * 将某个管理员踢下线
     */
    public function accountOffLine($accountId)
    {
        if (!request()->adminUser->is_administrators){
            return ResponseJson::error('您无权操作');
        }
        AccountService::accountOffLine($accountId);
        return ResponseJson::success();
    }

}